import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_give/tgpage/binding/reset.dart';
import 'package:flutter_give/tgpage/binding/wifi.dart';
import 'package:flutter_give/utils/LogUtils.dart';
import 'package:oktoast/oktoast.dart';
import 'package:rapid_kit/rapid_kit.dart';

import '../../common_ui/loading.dart';
import '../../pages/Home/home_vm.dart';
import '../../pages/auth/login_page.dart';
import '../../pages/subpackage/eqpagesave_page.dart';
import '../../pages/subpackage/firmware_page.dart';
import '../../repository/api.dart';
import '../../route/route_utils.dart';
import '../../theme.dart';
import '../../utils/lifecycle_aware.dart';
import '../../utils/snack_tips.dart';
import '../../widgets/global_widgets.dart';

/// 设备添加-二维码-扫码添加设备页面
class BindingByQrcodePage extends StatefulWidget {
  const BindingByQrcodePage({super.key});

  @override
  State<BindingByQrcodePage> createState() => _BindingByQrcodePageState();
}

class _BindingByQrcodePageState
    extends LifecycleAwareState<BindingByQrcodePage> {
  // 获取类
  HomeViewModel viewModel = HomeViewModel();

  bool _loading = false;
  bool _heard = false;

  String _wifiSsid = "";
  String _wifiPassword = "";
  String _bindingToken = "";

  String _bindingProfile = "";

  BindingStatePolling? _bindingStatePolling;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildTitleBar(context),
      body: _buildRootBody(context),
    );
  }

  @override
  void initState() {
    super.initState();
    // SystemChrome.setPreferredOrientations([
    //   DeviceOrientation.portraitUp,
    //   DeviceOrientation.portraitDown,
    // ]);

    WidgetsBinding.instance.addPostFrameCallback((_) {
      showToast("获取二维码临时token");
      _navigateToReset();
    });
  }

  @override
  void dispose() {
    super.dispose();

    _bindingStatePolling?.stop();

    // 恢复屏幕方向为默认
    // SystemChrome.setPreferredOrientations([
    //   DeviceOrientation.landscapeRight,
    //   DeviceOrientation.landscapeLeft,
    //   DeviceOrientation.portraitUp,
    //   DeviceOrientation.portraitDown,
    // ]);
  }

  Future<void> _navigateToReset() async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const ResetPage()),
    );

    if (!mounted) {
      return;
    }

    if (result == true) {
      _navigateToWifi();
    } else {
      Navigator.of(context).pop();
    }
  }

  Future<void> _navigateToWifi() async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const WiFiPage()),
    );

    if (!mounted) {
      return;
    }

    if (result.isNotEmpty) {
      List<String> parts = result.split('|||');
      _wifiSsid = parts.isNotEmpty ? parts[0] : '';
      _wifiPassword = parts.length > 1 ? parts[1] : '';

      _prepareBindingToken();
    } else {
      Navigator.of(context).pop();
    }
  }

  // 预添加设备获取token
  void _prepareBindingToken() async {
    final biningTokenResp = await BindingService.token();
    if (!mounted) return;
    if (biningTokenResp.success) {
      _bindingToken = biningTokenResp.data?.token ?? "";
      LogUtils.w("_bindingToken==${_bindingToken}");

      _bindingProfile =
          BindingService.profile(_wifiSsid, _wifiPassword, _bindingToken);

      LogUtils.w("_bindingProfile=${_bindingProfile}");
      setState(() {
        _bindingProfile = _bindingProfile;
        showToast("========二维码生成完毕========");
      });
    } else {
      RouteUtils.pushAndRemoveUntil(context, LoginPage());
      SnackTips.show(context,
          "无法获取绑定令牌：[${biningTokenResp.code}] ${biningTokenResp.message}");
      Future.delayed(const Duration(milliseconds: 1000), () {
        Navigator.of(context).pop();
      });
    }
  }

  void _startPollingState() {
    _bindingStatePolling?.stop();
    _bindingStatePolling = BindingStatePolling.create(_bindingToken);
    // 轮询-预添加设备接口-查询接口
    _bindingStatePolling?.listener = (resp) async {
      String stateTips = "";
      showToast("绑定数据${resp.code}${resp.message}${resp.data}");
      if (resp.code == 0) {
        // stateTips = "配网成功，设备ID ${resp.data}";
        stateTips = "";
        // _updateDeviceName(resp.data ?? "");

        // 同步设备数据

        // bool swtichdata = await Api.instance.equaldata();
        //
        // if (swtichdata) {
        //   showToast("===============设备同步成功===============");
        //   // 获取封面
        //   Api.instance.eqcoverimg(deviceid: "${resp?.data}");
        //   Navigator.push(
        //       context,
        //       MaterialPageRoute(
        //           builder: (context) => EqpagesavePage(
        //                 deviceId: resp.data ?? "",
        //                 deviceName: "",
        //                 ID: "",
        //               )));
        //   Loading.dismissAll();
        //   setState(() {
        //     _loading = false;
        //   });
        // }

        // 同步设备数据
        try {
          bool swtichdata = await Api.instance.equaldata(ID: "${resp.data}");

          if (swtichdata) {
            showToast("===============设备同步成功===============");
            // 获取封面
            Api.instance.eqcoverimg(deviceid: "${resp?.data}");
            // 设备重命名
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => EqpagesavePage(
                      deviceId: resp.data ?? "",
                      deviceName: "",
                      ID: "",
                    )));
            Loading.dismissAll();
            setState(() {
              _loading = false;
            });
          }
        } catch (e) {
          // 捕获异常并处理
          showToast("设备同步失败: $e");
          // Loading.dismissAll();
          setState(() {
            _loading = false;
          });
        }
      } else {
        if (resp.code == 400) {
          stateTips =
              "配网失败：${resp.code} ${resp.message ?? "未知错误"} - 确定二维码对准设备发出滴的一声";
        } else {
          stateTips = "配网失败：${resp.code} ${resp.message ?? "未知错误"}";
        }

        Loading.dismissAll();
        _showResult("$stateTips");
        setState(() {
          _loading = false;
        });
      }

      //
    };
    _bindingStatePolling?.start();
  }

  void _updateDeviceName(String deviceId) async {
    await SpecService.rename(deviceId, "未命名");
  }

  Future<void> _showResult(String tips) async {
    return showDialog<void>(
      context: context,
      barrierDismissible: false, // 设置为false，点击对话框外部无法关闭对话框
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('提示'),
          content: SingleChildScrollView(
            child: ListBody(
              children: <Widget>[
                Text(tips),
              ],
            ),
          ),
          actions: <Widget>[
            TextButton(
              child: const Text('我知道了'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  AppBar _buildTitleBar(BuildContext context) {
    return AppBar(
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios), // 使用没有横线的返回箭头图标
        onPressed: () {
          // 返回操作
          Navigator.of(context).pop();
        },
      ),
      title: const Text(
        '二维码配网',
        style: TextStyle(
          fontSize: 17,
          fontFamily: "PingFang SC",
          fontWeight: FontWeight.w600,
        ),
      ),
      // backgroundColor: SampleThemeConfigure.colorBackground,
      centerTitle: true,
      elevation: 0,
    );
  }

  Widget _buildRootBody(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        const Padding(
          padding: EdgeInsets.all(16.0),
          child: Text(
            '3.向设备的摄像头展示二维码，距离10-30厘米',
            style: TextStyle(
              fontSize: 14,
              color: SampleThemeConfigure.colorTextPrimary,
            ),
            textAlign: TextAlign.left,
          ),
        ),
        Expanded(
          child: Stack(
            children: [
              Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    _qrcode(),
                  ],
                ),
              ),
              if (_loading)
                Center(
                  child: Container(
                    color: Colors.black.withOpacity(0.7),
                  ),
                ),
              if (_loading)
                Center(
                  child: createCenterLoading(size: 20, color: Colors.white),
                ),
            ],
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(16.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Checkbox(
                value: _heard,
                activeColor: SampleThemeConfigure.colorPrimary,
                onChanged: (bool? value) {
                  setState(() {
                    if (_loading) return;
                    _heard = value!;
                  });
                },
              ),
              const Text('我已听到设备发出的提示音',
                  style: TextStyle(
                      color: SampleThemeConfigure.colorTextPrimary,
                      fontSize: 14)),
            ],
          ),
        ),
        Padding(
            padding: const EdgeInsets.all(16.0),
            child: SizedBox(
              height: 45,
              child: ElevatedButton(
                onPressed: (_heard && !_loading) ? _onNextStepTap : null,
                style: ElevatedButton.styleFrom(
                  backgroundColor: SampleThemeConfigure.colorPrimary,
                  foregroundColor: SampleThemeConfigure.colorForeground,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(30),
                  ),
                  padding:
                      const EdgeInsets.symmetric(horizontal: 80, vertical: 10),
                ),
                child: Text(_loading ? '绑定中...' : '绑定设备'),
              ),
            )),
      ],
    );
  }

  void _onNextStepTap() {
    if (_loading) return;

    Loading.showLoading();

    if (_heard) {
      _startPollingState();
      setState(() {
        _loading = true;
      });
    } else {
      SnackTips.show(context, "确认听到设备发出的提示音，再点击");
    }
  }

  Widget _qrcode() {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: LayoutBuilder(builder: (context, constraints) {
        return Container(
          width: constraints.maxWidth,
          height: constraints.maxWidth,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(8.0),
          ),
          child: Center(
            child: BindingService.qrcode(_bindingProfile,
                size: constraints.maxWidth * 0.9),
          ),
        );
      }),
    );
  }
}
